package com.example.servicelogin.controller;

import com.example.entity.vo.ResponseVO;
import com.example.login.dto.TokenUserInfoDto;
import com.example.servicelogin.services.UserInfoServie;
import com.example.servicelogin.services.impl.RedisServiceImpl;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/api/login")
public class UserLoginController extends ABaseController {
    @Autowired
    RedisServiceImpl redisService;
    @Autowired
    UserInfoServie userInfoServie;
    //验证码
    @RequestMapping("/checkCode")
    public ResponseVO checkCode() {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(100, 43);
//        验证码答案
        String code = captcha.text();
        System.out.println(code);
        String checkKey = UUID.randomUUID().toString();
        redisService.set("netty:checkcodekey"+checkKey,code.toString(),
                60 * 10) ;
//        图片验证码base64编码
        String cb64 = captcha.toBase64();
        Map<String, String> result = new HashMap<>();
        result.put("checkCode", cb64);
        result.put("key", checkKey);
        return getSuccessResponseVO(result);
    }

    //登录
    @RequestMapping("/login")
    public ResponseVO login(@NotEmpty String checkCodeKey,
                            @NotEmpty String username,
                            @NotEmpty String password,
                            @NotEmpty String checkCode) {
        System.out.println("11111111---"+checkCodeKey);
        System.out.println("22222222---"+username);
        System.out.println("33333333---"+password);
        System.out.println("44444444---"+checkCode);
        try {
//            equalsIgnoreCase用于比较两个字符串是否相等，同时忽略它们的大小写差异
//            判断传入 key 是否存在
            if (!checkCode.equalsIgnoreCase(
                    redisService.get("netty:checkcodekey"+checkCodeKey,String.class))) {
                return getBusinessErrorResponseVO("图片验证码错误");
            }
            
        } finally {
            redisService.del("netty:checkcodekey"+checkCodeKey);
        }
        //调用服务层登录方法  返回用户 id 及 token
        TokenUserInfoDto tokenUserInfoDto = userInfoServie.login(username, password);
        if (tokenUserInfoDto == null) {
            return getBusinessErrorResponseVO("用户名或密码错误");
        }
        return getSuccessResponseVO(tokenUserInfoDto);
    }



}
